/*
 * Copyright (c) 2001-2007, Inversoft, All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.inversoft.vertigo.database;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * <p>
 * This class runs a single SQL file using the semi-colon as
 * breaks between SQL statements.
 * </p>
 *
 * @author  Brian Pontarelli
 */
public class ScriptExecutor {
    private static final Logger logger = Logger.getLogger(ScriptExecutor.class.getName());
    private Connection connection;

    public ScriptExecutor(Connection connection) {
        this.connection = connection;
    }

    private void execute(InputStream is, String resource) throws IOException {
        logger.log(Level.INFO, "-- Running script resource [" + resource + "]");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        int len;
        char[] buffer = new char[4096];
        StringBuilder build = new StringBuilder();
        do {
            len = reader.read(buffer);
            if (len > 0) {
                build.append(buffer, 0, len);
            }
        } while (len != -1);

        reader.close();

        String[] sqlStatements = build.toString().split(";");
        for (String sqlStatement : sqlStatements) {
            if (sqlStatement.trim().length() > 0) {
                execute(sqlStatement, resource);
            }
        }
    }


    /**
     * Executes all of the SQL statments in the given file.
     *
     * @param   file The SQL script to execute.
     * @throws  IOException If the file couldn't be read or the file contained invalid SQL.
     */
    public void execute(File file) throws IOException {
        execute(new FileInputStream(file), file.getAbsolutePath());
    }

    /**
     * Executes all of the SQL statments in the given URL.
     *
     * @param   url The URL that points to an SQL script.
     * @throws  IOException If the file couldn't be read or the file contained invalid SQL.
     */
    public void execute(URL url) throws IOException {
        execute(url.openStream(), url.toString());
    }

    private void execute(String sqlStatement, String resource) throws IOException {
        try {
            Statement statement = connection.createStatement();
            System.out.println("Executing [" + sqlStatement + "]");
            statement.execute(sqlStatement);
            statement.close();
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "Error while executing SQL run from [" + resource +
                "]. The statement that failed was [" + sqlStatement + "]", e);
            throw new IOException("IO Exception occurred while executing sql from [" + resource +
                    "]: " + e.getMessage());
        }
    }
}